class WebSocketService {
    constructor(url) {
        this.url = url;
        this.socket = null;
        this.listeners = [];
    }
    
    connect() {
        this.socket = new WebSocket(this.url);
        
        this.socket.onopen = () => {
            console.log('WebSocket connected');
        };
        
        this.socket.onmessage = (event) => {
            this.listeners.forEach((listener) => listener(event.data));
        };
        
        this.socket.onclose = () => {
            console.log('WebSocket disconnected');
        };
        
        this.socket.onerror = (error) => {
            console.error('WebSocket error:', error);
        };
    }
    
    sendMessage(message) {
        if (this.socket && this.socket.readyState === WebSocket.OPEN) {
            this.socket.send(message);
        } else {
            console.error('WebSocket is not open. Ready state: ' + this.socket.readyState);
        }
    }
    
    addMessageListener(listener) {
        this.listeners.push(listener);
    }
    
    disconnect() {
        if (this.socket) {
            this.socket.close();
        }
    }
}

export default WebSocketService;
